package co.fitstart.mobile.web.controller.order;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.order.Order;
import co.fitstart.entity.order.OrderInvestigateRecord;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.fit.Shape;
import co.fitstart.entity.user.fit.UserFit;
import co.fitstart.entity.user.investigation.FitInvestigation;
import co.fitstart.mobile.service.InvestigationService;
import co.fitstart.mobile.service.OrderService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;
import co.fitstart.mobile.web.interceptor.WechatAuthority;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * @author wangliwang
 *
 */
@Controller
@RequestMapping("/orders/{orderId}/investigation-offlines")
public class OfflineInvestigationController {
    
    private static final Logger logger = LoggerFactory.getLogger(OfflineInvestigationController.class);
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private InvestigationService investigationService;

    /**
     * @param orderId
     * @return
     */
    @RequestMapping("")
    @Router
    @WechatAuthority(targetUrl = "/need-investigation")
    @MobileDetect
    @WechatJsConfig
    public ModelAndView index(@PathVariable("orderId") Long orderId) {
        
        ModelAndView modelAndView = new ModelAndView();
        
        // 1. find investigation record
        Order order = orderService.load(Order.class, orderId);
        OrderInvestigateRecord orderInvestigateRecord = orderService.loadOrderInvestigateRecord(order); 
        
        if (orderInvestigateRecord == null) {
            modelAndView.setViewName("redirect:/orders/" + orderId + "/investigation-offlines/error");
            return modelAndView;
        }
        
        // 2. check investigation whether finish
        if (orderInvestigateRecord.isFinish()) {
            modelAndView.setViewName("redirect:/orders/" + orderId + "/investigation-offlines/finish");
            return modelAndView;
        }
        
        // 3. goto fit investigation
        if(orderInvestigateRecord.needFitInvestigation()) {
            modelAndView.setViewName("redirect:/orders/" + orderId + "/investigation-offlines/fit");
            return modelAndView;
        }
        
        return modelAndView;
        
    }
    
    /**
     * @param user
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/fit", method = RequestMethod.GET)
    @Router
    @WechatAuthority(targetUrl = "/need-investigation")
    @MobileDetect
    @WechatJsConfig
    public ModelAndView fit(@Secure User user,
                            @PathVariable("orderId") Long orderId) {
        
        ModelAndView modelAndView = new ModelAndView("order/investigation/fit-investigation-offline");
        
        Order order = orderService.load(Order.class, orderId);
        UserFit userFit = user.getUserFit() == null ? new UserFit() : user.getUserFit();
        
        modelAndView.addObject("order", order);
        modelAndView.addObject("userFit", userFit);
        
        return modelAndView;
        
    }
    
    /**
     * @param user
     * @param orderId
     * @param shapeId
     * @param fitInvestigation
     * @return
     */
    @RequestMapping(value = "/fit", method = RequestMethod.PATCH)
    @Router
    @WechatAuthority
    @MobileDetect
    public @ResponseBody String onEditFit(@Secure User user,
                                          @PathVariable("orderId") Long orderId,
                                          @RequestParam("shapeId") Long shapeId,
                                          FitInvestigation fitInvestigation) {
        
        Result result = new Result();
        
        try {
            
            // 1. load Shape and investigation record
            Shape shape = investigationService.loadShape(shapeId);
            
            Order order = orderService.load(Order.class, orderId);
            OrderInvestigateRecord orderInvestigateRecord = orderService.loadOrderInvestigateRecord(order);
            
            // 2. edit fit
            investigationService.editOfflineFit(user, orderInvestigateRecord, fitInvestigation, shape, order);
            
            result.success().message("编辑身体数据成功");
            
        } catch (Exception e) {
            result.fail().message("编辑身体数据失败");
            logger.error("#onEditFit() - edit fit fail, exception is [{}]", e);
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * @return
     */
    @RequestMapping(value = "/error")
    public String error() {
        return "order/investigation/error";
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/finish")
    public ModelAndView finish() {
        ModelAndView modelAndView = new ModelAndView("order/investigation/finish");
        
        modelAndView.addObject("orderType", "offline");
        
        return modelAndView;
    }
    
}
